import axios from 'axiosInstance';
import router, { defaultMenuRoutes } from '@/router';
import routeMap from '@/router/routerMap';

// 根据获取的权限生成真实的路由
const generateRoutes = (result, parentPath = '') => {
  return result.map(item => {
    // 查找路由映射表对应的实例
    let { component, children } = item;
    const resultRoute = routeMap[component];
    if (component) {
      if (!resultRoute) {
        console.error(`路由映射表中未找到${item.component}对应的实例`);
      } else {
        // 修改 component 项
        item.component = resultRoute.component || '';
        //如果path没有/则添加
        if(!item.path.startsWith('/')){
          item.path = `/${item.path}`;
        }
      }
    }
    // 拼接父级路由的 path
    if (parentPath) {
      item.path = `${parentPath}/${item.path}`.replace(/\/+/g, '/');
    }
    // 递归处理子路由
    if (item.children) {
      item.children = generateRoutes(children, item.path);
    }
    return item;
  });
};

//添加路由
const addRoutesAction = (permissions) => {
  permissions.forEach(item => {
    router.addRoute('home', item); 
  })
  console.log(router.getRoutes(),'router');
}

// 过滤路由生成菜单路由
function filterDefaultRoutes(menuArray) {
  //如果路由有子路由 并且子路由只有一个则吧子路由替换掉父路由
  //深拷贝
  menuArray = JSON.parse(JSON.stringify(menuArray));
  return menuArray.map(item => {
    if (item.children && item.children.length === 1) {
      item = item.children[0];
    }
    return item;
  });
}

const state = {
  permissions: [],
  menuRouters: []
};

const mutations = {
  setPermissions(state, permissions) {
    state.permissions = permissions;
  },
  setMenuRouters(state, routers) {
    const defaultMenuRoute  = filterDefaultRoutes(defaultMenuRoutes);
    state.menuRouters = [...defaultMenuRoute, ...routers];
  }
};

const actions = {
  fetchPermissions({ commit }) {
    return axios.get(`/api/getRolesPermissions`)
      .then(response => {
        let permissions = response.data.permissions;
        // 生成路由信息关联到对应的组件生成真实的路由数据--》component项关联到了真实的组件
        permissions = generateRoutes(permissions);
        //进行路由添加操作
        addRoutesAction(permissions);
        //根据动态路由 和静态路由 生成菜单
        //generateMenu(permissions,defaultMenuRoutes);
        commit('setPermissions', permissions);
        commit('setMenuRouters', permissions);
        return permissions;
      })
      .catch(error => {
        throw error;
      });
  },
};

const getters = {
  getPermissions(state) {
    return state.permissions;
  },
  getMenuRouters(state) {
    return state.menuRouters;
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
